package com.xuecheng.system.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 全局跨域配置类  解决跨域问题
 * 此配置类实现了跨域过虑器，在响应头添加 Access-Control-Allow-Origin。
 *
 * @author jiang zhongxun
 * @create 2023-03-08 21:21
 */
@Configuration
public class GlobalCorsConfig {

    /**
     * 配置允许跨域调用的过滤器
     *
     * @return {@link CorsFilter}
     */
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 放行全部原始头信息
        corsConfiguration.addAllowedHeader("*");
        // 允许白名单域名进行跨域调用
        corsConfiguration.addAllowedOrigin("*");
        // 允许跨域发送 cookie
        corsConfiguration.setAllowCredentials(true);
        // 允许所有请求方法跨域调用
        corsConfiguration.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }

}
